<template>
  <div>
    <div>阵列立方体和相机适配体验</div>
    <div ref="webgl" id="webgl" style="width: 800px; height: 500px"></div>
  </div>
</template>
<script lang="ts" setup>
  import * as THREE from 'three';
  import { OrbitControls } from 'three/addons';
  import { onMounted, ref } from 'vue';

  const webgl: any = ref(null);
  onMounted(() => {
    init();
  });

  function init() {
    const scene = new THREE.Scene();
    const geometry = new THREE.BoxGeometry(10, 10, 10);
    //材质对象Material
    const material = new THREE.MeshLambertMaterial({
      color: 0x00ffff, //设置材质颜色
      transparent: true, //开启透明
      opacity: 0.5, //设置透明度
    });
    for (let i = 0; i < 10; i++) {
      for (let j = 0; j < 10; j++) {
        const mesh = new THREE.Mesh(geometry, material); //网格模型对象Mesh
        // 在XOZ平面上分布
        mesh.position.set(i * 15, 0, j * 15);
        scene.add(mesh); //网格模型添加到场景中
      }
    }

    // 环境光
    const alight = new THREE.AmbientLight(0xffffffff, 1);
    scene.add(alight);

    const light = new THREE.PointLight(0xffda0045, 10000.0);
    light.position.set(50, 100, 50);
    scene.add(light);
    //点光源辅助
    const pointLightHelper = new THREE.PointLightHelper(light, 6);
    scene.add(pointLightHelper);

    const helper = new THREE.AxesHelper(200);
    scene.add(helper);

    const width = innerWidth - 100;
    const height = innerHeight - 100;
    const camera = new THREE.PerspectiveCamera(30, width / height, 1, 10000);
    camera.position.set(300, 100, 300);
    camera.lookAt(50, 50, 50);
    const render = new THREE.WebGLRenderer();
    //   render.setClearColor(0x123adf, 0.2);
    render.setSize(width, height);
    webgl.value.appendChild(render.domElement);

    render.render(scene, camera);
    const controls = new OrbitControls(camera, render.domElement);
    // 相机控件.target属性在OrbitControls.js内部表示相机目标观察点，默认0,0,0
    // console.log('controls.target', controls.target);
    controls.target.set(50, 50, 50);
    controls.update(); //update()函数内会执行camera.lookAt(controls.targe)

    function renderFun() {
      render.render(scene, camera);
      requestAnimationFrame(renderFun);
    }
    renderFun();
  }
</script>
